package com.wanxi.servlet;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import com.alibaba.fastjson.JSONObject;
import com.wanxi.dto.ResultDto;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/code")
public class CodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(130, 45, 4, 100);
        RandomGenerator randomGenerator = new RandomGenerator("0123456789abcdecghigklmzobqrstuvwsyz", 4);  //生成4个随机数
        lineCaptcha.setGenerator(randomGenerator);
        lineCaptcha.createCode();
//        req.setAttribute("aa","aa");
        String code = lineCaptcha.getCode();  //获取验证码
        req.getSession().setAttribute("sCode", code);
        resp.getWriter().println(JSONObject.toJSONString(ResultDto.getInstance("data:image/png;base64," + lineCaptcha.getImageBase64().toString())));
    }
}
